package edu.hnu.tradeserver.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.hnu.commonutils.Result;
import edu.hnu.tradeserver.entity.Test;
import edu.hnu.tradeserver.service.TestService;
import edu.hnu.tradeserver.mapper.TestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import java.util.List;


@Service
public class TestServiceImpl extends ServiceImpl<TestMapper, Test>
    implements TestService{
    @Autowired
    TestMapper testMapper;
    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Override
    public Result addTradeRecord(Test test) {
        int result = testMapper.insert(test);
        System.out.println(test);
        if(result==0) {
            return Result.error().data(test);

        }
        else
        return Result.ok().data(test);
    }

    @Override
    public Result stocksInfo() {
        StringBuilder sb = null;
        List<String> serviceIds = discoveryClient.getServices();
        if(CollectionUtils.isEmpty(serviceIds))
            return null;

        List<ServiceInstance> serviceInstances = discoveryClient.getInstances("product-server");
        if(CollectionUtils.isEmpty(serviceInstances))
            return null;

        ServiceInstance si = serviceInstances.get(0);
        sb = new StringBuilder();
        sb.append("http://"+si.getHost()+":"+si.getPort()+"/stocksInfo");
        ResponseEntity<Result> response = restTemplate.exchange(
                sb.toString(),
                HttpMethod.GET,
                null,
                new ParameterizedTypeReference<Result>() {}
        );
        return Result.ok().data(response.getBody().getData());
    }
}




